/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-21 10:06:56
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-08-09 10:47:57
 * @FilePath: \vite-project\src\layout\Root.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom';

// store
import { Dropdown, Layout, Space, Modal, Spin, Avatar, Tabs, Menu, Badge,message } from 'antd';
import { Icon } from '@iconify/react';
import { useEffect } from 'react';
import useUserStore, { useTokenStore } from '../store/user';

// commponent

// utils
import { findLeafNodes } from '../utils/helper';
import useLogin from '../hooks/useLogin';
import logoSvg from '@/assets/logo.svg';
import KeepAliveLayout from '@/components/common/KeepAliveLayout/Index';
import NoticeMessage from '@/components/common/NoticeMessage';
import UserHelp from '@/components/common/UserHelp';

const { Header } = Layout;

export default function Root() {
    const { token } = useTokenStore();
    const [messageApi] = message.useMessage();
    const { userInfo, menus, menuMap, menuPaths, firstPath, pageTabs, updatePageTabs } = useUserStore();
    const { handleLogin, claerToken } = useLogin();
    const { pathname } = useLocation();
    const navigate = useNavigate();
    const items: any[] =
        userInfo?.roles?.map((item) => ({
            label: item.organizationFullName,
            value: item.organizationId,
            onClick: () => handleClick(item),
        })) || [];

    const handleClick = (item: any) => {
        // 切换组织机构树
        Modal.confirm({
            title: '提示',
            content: `确定要切换组织机构至【${item.organizationFullName}】吗`,
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk() {
                return new Promise<void>(async (resolve, reject) => {
                    try {
                        messageApi.success('切换成功');
                        resolve();
                        location.reload();
                    } catch (error) {
                        reject();
                    }
                });
            },
        });
    };
    const handleLogout = () => {
        Modal.confirm({
            title: '提示',
            content: '确定退出登录吗？',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk() {
                claerToken();
                handleLogin();
            },
            onCancel() {},
        });
    };

    const usetItems = [
        {
            key: '1',
            label: (
                <div className='flex items-center cursor-pointer' onClick={handleLogout}>
                    <Icon icon='ant-design:login-outlined' />
                    <span className='ml-4px'>退出登录</span>
                </div>
            ),
        },
        // {
        // 	key: '2',
        // 	label: (
        // 		<div className="flex items-center cursor-pointer">
        // 			<Icon icon="ant-design:user-outlined"></Icon>
        // 			<span className="ml-4px">切换组织机构</span>
        // 		</div>
        // 	),
        // },
    ];

    useEffect(() => {
        // 是否登录
        if (!token) {
            handleLogin();
        }
    }, [token]);

    useEffect(() => {
        if (firstPath && pathname === '/') {
            navigate(firstPath, {
                replace: true,
            });
        }
    }, [firstPath]);

    if (!token) {
        return (
            <Spin size='large' className='!max-h-screen'>
                <div className='h-screen' />
            </Spin>
        );
    }

    return (
        <KeepAliveLayout>
            <Layout className='min-h-screen flex flex-col w-full'>
                <Header className='flex items-center justify-between px-0px sticky top-0 z-999 box-shadow-nav-header'>
                    <Link to={findLeafNodes(menus?.[0])?.[0]?.path}>
                        <div className='relative flex items-center pl-10px w-249px'>
                            <img src={logoSvg} className='ml-20px' />
                            <span className='absolute left-136px font-bold text-16px text-black'>无人质检标注</span>
                        </div>
                    </Link>
                    <div className='flex-1 w-0 overflow-x-auto overflow-y-hidden'>
                        <Tabs
                            className='zy-nav-menu mt-15px'
                            defaultActiveKey={`/${pathname?.split('/')[1]}`}
                            items={menus?.map((item, index) => ({
                                label: (
                                    <Link
                                        to={findLeafNodes(item)?.[0]?.path}
                                        className={`flex items-center group h-30px rounded-4px px-16px ${
                                            pathname?.startsWith(item?.path) ? 'bg-primary  !text-white' : 'text-black'
                                        } `}
                                    >
                                        {item.icon}
                                        <span
                                            className={`ml-6px text-16px ${
                                                pathname?.startsWith(item?.path) ? 'bg-primary text-white' : ''
                                            } `}
                                        >
                                            {item.label}
                                        </span>
                                    </Link>
                                ),
                                key: item?.key,
                            }))}
                        />
                    </div>
                    <Space className='px-12px pr-24px'>
                        <NoticeMessage />
                        <UserHelp />
                        <Dropdown menu={{ items: usetItems }} trigger={['hover']} arrow>
                            <div className='flex items-center cursor-pointer bg-primaryBg h-38px px-7px rounded-38px group'>
                                <Avatar className='w-24px h-24px bg-primary mr-8px'>{userInfo?.name}</Avatar>
                                <div className='mr-8px'>{userInfo?.name}</div>
                                <Icon icon='ant-design:caret-down-filled' className='group-hover:rotate-180 transform transition-all' />
                            </div>
                        </Dropdown>
                    </Space>
                </Header>

                <div className='flex-1'>
                    <Outlet />
                </div>
            </Layout>
        </KeepAliveLayout>
    );
}
